<template>
  <div class="face-demo">
    <template>
      <div
        v-if="mode === 'edit'"
        style="margin: 10px 0 0 0;"
      >
        <van-button
          type="info"
          round
          :disabled="disabled"
          :loading="mobileBtnLoading"
          @click="requestWstInterface"
        >{{ btnText }}</van-button>
      </div>
      <div v-else>{{ value }}</div>
    </template>
  </div>
</template>

<script>
// window.hydra = window.croods = require("../../utils/wst_hydra_1.0.1.js").croods;
import { loadRemoteComponent } from '@/utils/loadRemote.js'
import axios from "axios"
import customRequest from "../../mixins/custom-request.js"
const mfpConfig = require('../../../build/mfp.config.js')
export default {
  name: 'face',
  components: {},
  mixins: [customRequest],
  props: {
    value: {},
    mode: {
      default: "edit", // 编辑模式和 edit， 展示模式 view
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    // appCode: {
    //   type: String,
    //   default: "",
    // },
    // appSecret: {
    //   type: String,
    //   default: "",
    // },
    // faceComponentUrl: {
    //   type: String,
    //   default: "",
    // },
    // contextPath: {
    //   type: String,
    //   default: "",
    // },
    // fvTokenPath: {
    //   type: String,
    //   default: "",
    // },
    // faceResultPath: {
    //   type: String,
    //   default: "",
    // },
  },
  data() {
    return {
      btnText: "人脸识别",
      timer: null,
      interval: 5 * 1000,
      mobileBtnLoading: false,
      loadJsed: false,
      belong: '人脸识别',
    }
  },
  computed: {},
  watch: {},
  created() {
    const { name } = mfpConfig;
    loadRemoteComponent({ url: `${this.preurl}api/afc/components/${name}/assets/js/wst_hydra_1.0.1.js` }).then(() => {
      this.loadJsed = true;
    })
  },
  mounted() {
    if (this.value) {
      this.btnText = this.value;
      if (this.mode == "view") {
        this.disabled = true;
      }
    }
  },
  methods: {
    stopInterval() {
      clearInterval(this.timer)
      this.timer = null
    },
    queryResult(token, headers) {
      // const { faceComponentUrl, contextPath, faceResultPath, appCode, appSecret } = this;
      const faceComponentUrl = this.getCodeValueByCode('FACE_COMPONENT_URL')
      const contextPath = this.getCodeValueByCode('CONTEXT_PATH')
      const faceResultPath = this.getCodeValueByCode('GET_ACCESS_CHECK_URL')
      const appCode = this.getCodeValueByCode('APP_CODE')
      const appSecret = this.getCodeValueByCode('APP_SECRET')
      const data = { faceComponentUrl, contextPath, faceResultPath, appCode, appSecret, accessToken: token }
      axios.post(`${this.preurl}api/afc/integration/accessCheck`, data, { headers }).then((res) => {
        const responseData = _.get(res, 'data', null)
        console.log("accessCheck接口成功响应数据:", responseData)
        const { errCode, errMsg } = responseData;
        if (errCode === "20000" || errCode === 20000) {
          this.stopInterval()
          this.mobileBtnLoading = false;
          this.$toast.success("认证成功")
        } else {
          this.$toast.fail(errMsg)
        }
      }).catch((err) => {
        console.log("请求accessCheck接口错误:", err)
      })
    },
    requestWstInterface() {
      if (!this.loadJsed) {
        console.log("wst活体检测前端插件加载失败")
        return
      }
      this.mobileBtnLoading = true;
      try {
        // alert(typeof croods.customPlugin)
        croods.customPlugin({
          action: "UserPlugin.login",
          params: {},
          success: (res) => {
            if (res && res.token) {
              const { token } = res;
              const headers = this.header
              // const { faceComponentUrl, contextPath, fvTokenPath, appCode, appSecret } = this;
              const faceComponentUrl = this.getCodeValueByCode('FACE_COMPONENT_URL')
              const contextPath = this.getCodeValueByCode('CONTEXT_PATH')
              const fvTokenPath = this.getCodeValueByCode('GET_FV_TOKEN_URL')
              const appCode = this.getCodeValueByCode('APP_CODE')
              const appSecret = this.getCodeValueByCode('APP_SECRET')
              const data = { faceComponentUrl, contextPath, fvTokenPath, appCode, appSecret, token, isApp: true }
              console.log("getFaceToken接口入参:", data)
              axios.post(`${this.preurl}api/afc/integration/getFaceToken`, data, { headers }).then((resp) => {
                const { data, errCode, errMsg } = resp.data;
                const { fvtoken, key } = data;
                console.log("成功响应数据:", data)
                if (errCode !== "20000") {
                  this.mobileBtnLoading = false;
                  this.$toast.fail(errMsg)
                  return;
                }
                if (fvtoken && key)
                  hydra.customPlugin({
                    action: "WstFacePlugin.faceConfirmParams",
                    params: { fvtoken, key },
                    success: (res) => {
                      if (res && res.accessToken) {
                        const { accessToken } = res;
                        this.stopInterval();
                        this.timer = setInterval(() => {
                          setTimeout(this.queryResult(accessToken, headers), 0)
                        }, this.interval)
                      }
                    },
                    fail: (msg) => {
                      console.log("人脸活体检测失败----:", msg)
                      this.mobileBtnLoading = false;
                      this.$toast.fail(msg)
                    },
                  });
              }).catch((err) => {
                console.log("请求getFaceToken接口错误:", err)
                this.mobileBtnLoading = false;
                const message = _.get(err, "response.data.errorLocalizedMessage")
                this.$toast.fail(message || err.message)
              })
            }
          },
          fail: (msg) => {
            console.log("单点登录获取token失败:", msg)
            this.mobileBtnLoading = false;
            this.$toast.fail(msg)
          },
        });
      } catch (e) {
        console.log("调用过程报错了:", e)
        this.mobileBtnLoading = false;
        this.$toast.fail(e.message)
      }
      // } finally {
      //   alert("调用完成")
      // }
    },
  },
};
</script>
<style lang="scss" scoped>
.face-demo {
  width: 100%;
}
</style>